<%@page import="java.util.Arrays"%>
<%@page import="java.util.ArrayList"%>
<%@ page import = "num.WebManager" %>
<%@ page import = "org.ntu.csn.as.manager.DBManager" %>

<jsp:useBean id="n" class="num.WebManager" scope="session"/>
<jsp:useBean id="db" class="org.ntu.csn.as.manager.DBManager" scope="session"/>
<%!
    String nonull(String s) {
        return (s == null) ? "" : s;
    }

    String nospace(String s) {
        return s.replaceAll("\\s+", "");

    }

    class Solution {

        public int qid;
        public String qtype;
        public boolean hasFraction = false;
        public ArrayList<String> SolExplList = new ArrayList<String>();
        public ArrayList<String> SolExprList = new ArrayList<String>();
    }
%>
<%
    //handle interfacing with back-end
    ArrayList<String> VarList = new ArrayList<String>();
    ArrayList<String> RelList = new ArrayList<String>();
    ArrayList<String> SolList = new ArrayList<String>();
    ArrayList<Solution> SolAll = new ArrayList<Solution>();//temp storage for solutions
    //VarList = n.getVariableList();
    //RelList = n.getRelationList();
    //SolList = n.getSolutionList();
    int var_count;
    int numqs = 0;
    String dod = "review";
    String qid = "0", marks = "5";
    String qtype = "WholeNumber";
    String[] CatListSel = new String[10];
    String[] TplListSel = new String[100];

    if (request.getParameter("doPra") != null) {
        dod = "practice";
    }

    if (request.getParameter("submit") != null) {
        if (request.getParameter("submit").contains("")) {
            String numq = request.getParameter("numqs");
            CatListSel = request.getParameterValues("category");
            TplListSel = request.getParameterValues("myid");
            marks = request.getParameter("marks");
            numqs = Integer.valueOf(numq);
            SolAll.clear();
        }
    }
%>
<html>

    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <style media="screen" type="text/css">
            .waiting_div_class { position: absolute; z-index: 1; top: 100px; left: 400px; display: block; }
            .question_table_div_class { display: none;}
            .row_selected {color:red;}
        </style>

        <title>Question Manager</title>
        <script type="text/javascript">  
            function showsol(boxid){
                document.getElementById("solution"+boxid).style.display="block";
                document.getElementById("hide"+boxid).style.display="block";
                document.getElementById("show"+boxid).style.display="none";
            }

            function hidesol(boxid){
                document.getElementById("solution"+boxid).style.display="none";
                document.getElementById("hide"+boxid).style.display="none";
                document.getElementById("show"+boxid).style.display="block";
            }
            function expand(id) {
                var el=document.getElementById(id);
                if (el.style.display!="none"){
                    el.style.display="none";
                }else{
                    el.style.display="block";
                }
            }
        </script>
    </head>
    <body bgcolor="white">
        <div id="waiting_div" class="waiting_div_class">
            <table width="100%">
                <tr>
                    <td align="center"><strong><em>Please wait while loading......</em></strong></p></td>
                </tr>
            </table>
        </div>
        <%@include file="tpl_header.jsp"%>
        <table width="100%" border="0">
            <tr>
                <td width="65%">  
                    <form action="" method=post>
                        <!-- hj: show option panel -->
                        <% if (dod.equals("practice")) {%>
                        <% ArrayList<String> CatList = db.getQuestionTypAll();%>
                        <div >
                            <label >Question Types:</label>
                            <% for (var_count = 0; var_count < CatList.size(); var_count++) {
                                String chked = "";%>
                            <% if (CatListSel != null && CatListSel.length > 0 && Arrays.asList(CatListSel).contains(CatList.get(var_count))) {
                                    chked = "checked";
                                }%>
                            <input type="radio" title="Click here to select a topic and you can also select one or more question types. If none is selected, all questions of this topic will be presented. " class="category_checkbox" name="category" value="<%=CatList.get(var_count)%>" <%=chked%> /><%=CatList.get(var_count)%>                
                            <%}%>
                        </div>       
                        <%}%>

                        <!-- hj: end of type selection section -->
                        <div id="typelist_div" class="typelist_div_class" style="display:none">
                            <%@include file="TypeList.jsp"%>
                        </div>
                        <!-- hj: end of type selection section -->
                        <p></p><label>Number of  questions to generate :</label><input  type="text" name=numqs size="5" maxlength="3" value=<%if (numqs == 0) {%>"10"<%} else {%><%=numqs%><%}%>>
                        <input type=hidden name=marks size="2" maxlength="4" value="50">
                        <p></p>
                        <div id="ShowNavButtons">
                            <div style="float:left;"><input id="genQuestion_but" class="genQuestion_but" name="submit" type=submit value="<% if (numqs == 0) {%>Generate<% } else {%>More<%}%> <%=dod%> exercises"></div>
                            <div id="PrintButton" style="float:left;width: 300px;font-size:0.825em;">
                                <input type="radio" title="Default page view. Show 'Show Solution' button at each question." class="print_op_radio" name="print_op_radio" value="pdefault" checked="checked" />Default
                                <input type="radio" title="Show all solutions. Select this if you want to print with all solutions." class="print_op_radio" name="print_op_radio" value="pwithsol" />With Solutions
                                <input type="radio" title="Show no solutions. Select this if you want to print with no solutions." class="print_op_radio" name="print_op_radio" value="pwithosol" />Without Solution
                            </div>
                        </div>
                        <% if ((CatListSel == null)) {%>
                        <p><label>Generating questions from <b>All Topics</b>. </label></p>
                        <%} else if ((TplListSel == null)) {%>
                        <p><label>Generating questions from <b><%=CatListSel[0]%>. All question types.</b> </label></p>
                        <%} else if ((TplListSel != null && TplListSel.length > 0 && TplListSel[0] != null)) {%>
                        <p><label>Generating questions from <b><%=CatListSel[0]%>:
                                    PSP<%=TplListSel[0]%>
                                    <% for (int i = 1; i < TplListSel.length; i++) {%>
                                    -PSP<%=TplListSel[i]%>
                                    <%}%>                        
                                </b>. </label></p>
                                <%}%>


                        <hr />
                        <div id="question_table_div" class="question_table_div_class"><p></p>
                            <div class="dataTables_wrapper" id="question_container">
                                <table class="dataTable"  id="question_table">
                                    <thead >
                                        <tr>    
                                            <th >ID</th>
                                            <th >Question</th>
                                        </tr>
                                    </thead>
                                    <tbody>


                                        <%

                                            int TplIndex = 0; /* hj show the tpl one by one */
                                            for (var_count = 0; var_count < numqs; var_count++) {

                                                if (TplListSel != null && TplListSel.length > 0) {
                                                    /*hj: ok only some tempaltes selected */
                                                    if (TplIndex >= TplListSel.length) {
                                                        TplIndex = 0;
                                                    }
                                                    qid = TplListSel[TplIndex++];
                                                }

                                                /* avoid duplication */
                                                for (int i = 0; i < 10 && TplIndex == 0; i++) {
                                                    String newqid = String.valueOf(db.getRandomQuestion(CatListSel));
                                                    if (!newqid.equals(qid)) {
                                                        qid = newqid;
                                                        break;
                                                    }
                                                }
                                                qtype = db.getQuestionTyp(qid);
                                                n.setQQtype(qtype);

                                                int tpl_id = db.getRandomTemplate(qid);
                                                if (tpl_id != -1) {
                                                    n.setQuestion0(db.getQuestion(qid, tpl_id));
                                                } else {
                                                    n.setQuestion0(db.getQuestion(qid));
                                                }
                                                VarList = db.getDefinition(qid);
                                                for (int i = 0; i < VarList.size(); i++) {
                                                    n.setVariable(VarList.get(i));
                                                }
                                                RelList = db.getRelation(qid);
                                                for (int i = 0; i < RelList.size(); i++) {
                                                    n.setRelation(RelList.get(i));
                                                }
                                                SolList = db.getSolution(qid);
                                                for (int i = 0; i < SolList.size(); i++) {
                                                    n.setSolution(SolList.get(i));
                                                }

                                        %> 
                                        <tr>
                                            <td><%=var_count + 1%></td>
                                            <td><%=n.getQuestion1(0)%>
                                                <p style="display:none" align="right">(<%=marks%> Marks) </p>
                                                <div align="right">
                                                    <input class="butshow" type="button"   value="Show Solution" id="<%="show" + var_count%>" onclick="showsol('<%=var_count%>')"></input>
                                                    <input class="buthide" type="button" value="Hide Solution" style="display:none" id="<%="hide" + var_count%>"  onclick="hidesol('<%=var_count%>')"></input>
                                                    <p>&nbsp;</p>
                                                </div>

                                                <%
                                                    Solution testSol = new Solution();
                                                    for (int solstep = 0; solstep < SolList.size(); solstep++) {
                                                        // hj store the solution    
                                                        String SolExpl = n.getSolutionExpl(SolList.get(solstep), 1);
                                                        String SolExpr = n.getSolutionExprNum(SolList.get(solstep));

                                                        testSol.qid = var_count;
                                                        testSol.qtype = qtype;
                                                        testSol.hasFraction = n.hasFraction();
                                                        testSol.SolExplList.add(SolExpl);
                                                        testSol.SolExprList.add(SolExpr);
                                                        //hj store the solution end
                                                    }

                                                    SolAll.add(testSol);
                                                %>


                                                <div class="soldiv"style="display:none;background: #cccccc" id=<%="solution" + var_count%>>
                                                    <h5><i>Detailed Solution:</i></h5>
                                                    <% for (int var_count2 = 0; var_count2 < SolList.size(); var_count2++) {%> 
                                                    <%=n.getSolutionExpl(SolList.get(var_count2), 1)%> :<p>                            
                                                        <%=n.MeDi(n.getSolutionExprNum(SolList.get(var_count2)))%> = 
                                                        <% if (qtype.equalsIgnoreCase("Algebra")) {%>
                                                        <%=n.MeDi(db.doAlgCalculation((n.getSolutionExprNum(SolList.get(var_count2))), false))%><p>
                                                        <%} else {
                                                            if (n.hasFraction()) {%>
                                                        <%=n.MeDi(db.doCalculation((n.getSolutionExprNum(SolList.get(var_count2))), true))%><p>
                                                        <%} else {%>
                                                        <%=n.MeDi(db.doCalculation((n.getSolutionExprNum(SolList.get(var_count2)))))%><p>
                                                        <%}%>
                                                        <%}
                                                            }%>
                                                        <input class="buthide" type=button value="Hide Solution" onclick="hidesol('<%=var_count%>')" id=<%="show" + var_count%> ></input>
                                                </div>
                                                <p>&nbsp;</p>
                                                <p>&nbsp;</p>
                                            </td>
                                        </tr>

                                        <%  }%>
                                    </tbody>
                                </table>
                            </div> <!-- hj: end of question table -->
                        </div>

                        <!--
                        <label style="display:none"><b>Detailed Solutions.</b></label></p> 
                        <% if (false) {//hj no all solution
                                for (var_count = 0; var_count < numqs; var_count++) {
                                    Solution testSol = SolAll.get(var_count);
                        %>
                        <b>Q<%=var_count + 1%>.  </b> <p>
                        <%
                            for (int var_count2 = 0; var_count2 < testSol.SolExprList.size(); var_count2++) {
                                String SolExpl = testSol.SolExplList.get(var_count2);
                                String SolExpr = testSol.SolExprList.get(var_count2);
                        %>
                        <%=SolExpl%> <br>                           
                        <%=SolExpr%> = 
                        <% if (testSol.qtype.equalsIgnoreCase("Algebra")) {%>
                        <%=db.doAlgCalculation(SolExpr, false)%><p>
                        <% } else {%>
                        <% if (testSol.hasFraction) {%>
                        <%=db.doCalculation(SolExpr, true)%><p>
                        <%} else {%>
                        <%=db.doCalculation(SolExpr)%><p>
                        <%}
                                        }
                                    }

                                }
                            }//if 0
%>
                        -->
                        <%

                            if (numqs > 0) {
                                n.reset();
                            }
                        %>	                   
                        <% if (numqs > 0) {%>	
                        <input class="genQuestion_but" name="submit" type=submit value="More <%=dod%> exercises"><p>
                            <button onclick="document.location.href='QuestionGen.jsp'; return false;">Back to Main</button>
                            <% }%>
                    </form>
                </td>
            </tr>
        </table>
        <table>
            <tr>  
                <td>
                    <%if (!n.getHint().equals("no hint")) {
                    %>
                    <font color="red"><%=n.getHint()%></font><br>
                    <%}
                    %>
                </td>
            </tr>
        </table>


        <%@include file="tpl_footer.jsp"%>
    </body>
    <script type="text/javascript"><!--
        //start generating questions
        $('.genQuestion_but').click(function() {
            $('#waiting_div').show('fast');
            $('#question_table_div').hide('fast', function() {
            });
        });
        //show the question types belong to this category type
        $('.category_checkbox').click(function() {
            $('#typelist_div').show('fast', function() {
            });
            listTable.fnFilter( $(":checked").val());
        });
 

        var oTable;
        var listTable;
        $(document).ready(function() {    
            //show the solution based on selection
            $('.print_op_radio').click(function() {
                $('#waiting_div').show('fast');
                var oSettings = oTable.fnSettings();
                var oldLength= oSettings._iDisplayLength;
                oSettings._iDisplayLength = -1;
                oTable.fnDraw();
                if ($(".print_op_radio:checked").val()=="pwithsol"){
                    $('.soldiv').show('fast');
                    $('.butshow').hide('fast');
                    $('.buthide').hide('fast');
                }else if ($(".print_op_radio:checked").val()=="pwithosol"){
                    $('.soldiv').hide('fast');
                    $('.butshow').hide('fast');
                    $('.buthide').hide('fast');
                }else{
                    $('.soldiv').hide('fast');
                    $('.butshow').show('fast');
                    $('.buthide').hide('fast');
                }
                oSettings._iDisplayLength = oldLength;
                oTable.fnDraw();
                $('#waiting_div').hide('fast');
            });

            listTable = $('#type_table').dataTable( {
                "bProcessing": true,
                "bServerSide": false,
                "aaSorting": [],
                "aLengthMenu" : [ 5,10, 25, 50],
                "sDom" : '<"top">rt<"bottom">',
                "bAutoWidth": false,
                "aoColumns": [
                    { "bSortable": false },
                    { "bSortable": false },
                    { "bSortable": false }
                ],
                "iDisplayLength": -1
            } );


            //hj: start table display
            oTable = $('#question_table').dataTable( {
                "bProcessing": true,
                "bServerSide": false,
                "aaSorting": [],
                "aLengthMenu" : [ [ 5, 10, 20, -1 ], [ 5, 10, 20, 'All' ] ],
                "sDom" : '<"top"lp>rt<"bottom"ip>',
                "bAutoWidth": false,
                "aoColumns": [
                    { "bSortable": false },
                    { "bSortable": false }
                ],
                "iDisplayLength": 5
            });
        
            var oTableTools = new TableTools( oTable, {
                "sSwfPath": "js/TT/media/swf/copy_cvs_xls_pdf.swf",
		
                "aButtons": [ {
                        "sAction": "print",
                        "sExtends": "print",
                        "sInfo": "<h6>Press Esc to return</h6><p>Use your browser's print function to "+
                            "print this table.",
                        "sButtonText": "Print Exam Paper"
                    } ]
            } );	
            $('#PrintButton').before( oTableTools.dom.container );
            //hj end table display
        
            $('#waiting_div').hide('fast', function() {
            });
            $('#question_table_div').show('fast', function() {
            });

        } );
        //--></script>
</html>


